<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\command;


use app\common\model\callback\OrderCallback;
use app\common\model\order\Order;
use app\common\model\recycle_report\RecycleReportDetail;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;


class SyncReportDetail extends Command
{
    protected function configure()
    {
        $this->setName('sync_report_detail')
            ->setDescription('更新订单报表信息');
    }


    protected function execute(Input $input, Output $output)
    {
        try {
            $orderBackList = OrderCallback::where('promotion_link_id'>0)->select();
            foreach ($orderBackList as $item){
                $money = Order::where('id',$item->order_id)->value('money')??0;
                dump("更新订单报表明细 订单ID-" . $item['order_id']);
                $date = date('Y-m-d',strtotime($item->create_time));
                $dyeing_date = date('Y-m-d',strtotime($item->dyeing_time));
                $diff = abs(strtotime($date) - strtotime($dyeing_date));
                // 将差值转换为天数 然后+1
                $day = floor($diff / (60 * 60 * 24))+1;
                //根据推广链，染色日期，天数 3个参数判断数据是否存在，存在就更新，不存在插入
                $recycleReportDetail = RecycleReportDetail::where(['promotion_link_id'=>$item->promotion_link_id,'day'=>$day,'count_date'=>$dyeing_date])->findOrEmpty();
                if ($recycleReportDetail->isEmpty()){
                    $recycleReportDetailData = [
                        'promotion_link_id'=>$item->promotion_link_id,
                        'day'=>$day,
                        'count_date'=>$dyeing_date,
                        'recharge_money'=>$money,
                    ];
                    RecycleReportDetail::create($recycleReportDetailData);
                }else{
                    $recycleReportDetail->recharge_money += $money;
                    $recycleReportDetail->save();
                }
            }
            $output->writeln('sync_report_detail');
            return true;
        } catch (\Exception $e) {
            Log::write('失败,失败原因:' . $e->getMessage());
            return false;
        }
    }

}